<template>
  <div class="max-w-7xl px-4 sm:px-6 lg:px-8 py-6">
    <!-- 头部信息区域 - 响应式布局 -->
    <div class="bg-white dark:bg-dark-primary rounded-lg shadow-soft p-6 mb-6">
      <div class="flex items-center mb-6">
        <svg class="w-6 h-6 text-primary-500 mr-3" aria-hidden="true">
          <use xlink:href="#icon-a-icon_FolderOpen"></use>
        </svg>
        <span
          class="text-2xl font-heading font-semibold text-gray-900 dark:text-gray-100"
          >资料</span
        >
      </div>

      <!-- 桌面端布局 -->
      <div class="hidden md:block">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 items-end">
          <div class="space-y-2">
            <span class="text-sm font-medium text-gray-600 dark:text-gray-300"
              >容量：{{ useflow.usesize }} / {{ useflow.size }}</span
            >
            <div class="w-full">
              <el-progress
                :percentage="useflow.percentagesize"
                :color="
                  useflow.percentagesize > 80
                    ? '#ef4444'
                    : useflow.percentagesize > 60
                    ? '#f59e0b'
                    : '#3b82f6'
                "
                :stroke-width="8"
                class="!mb-0"
              />
            </div>
          </div>
          <div class="space-y-2">
            <span class="text-sm font-medium text-gray-600 dark:text-gray-300"
              >月流量：{{ useflow.useflow }} / {{ useflow.flow }}</span
            >
            <div class="w-full">
              <el-progress
                :percentage="useflow.percentageflow"
                :color="
                  useflow.percentageflow > 80
                    ? '#ef4444'
                    : useflow.percentageflow > 60
                    ? '#f59e0b'
                    : '#3b82f6'
                "
                :stroke-width="8"
                class="!mb-0"
              />
            </div>
          </div>
          <div class="flex justify-end">
            <el-upload
              class="inline-block"
              :disabled="!!percentage"
              action="https://jsonplaceholder.typicode.com/posts/"
              :auto-upload="true"
              :http-request="request"
              :show-file-list="false"
            >
              <el-button
                :disabled="!!percentage"
                ref="buttonRef"
                size="default"
                type="primary"
                class="!px-6 !py-3"
              >
                <el-icon :size="20">
                  <Upload />
                </el-icon>
                <span class="ml-2">
                  {{ percentage ? "上传中..." + percentage + "%" : "上传文件" }}
                </span>
              </el-button>
            </el-upload>
          </div>
        </div>
      </div>

      <!-- 移动端布局 -->
      <div class="block md:hidden">
        <div class="space-y-4">
          <div class="grid grid-cols-1 gap-4">
            <div class="bg-gray-50 dark:bg-dark-secondary rounded-lg p-4">
              <div
                class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"
              >
                容量
              </div>
              <div
                class="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-2"
              >
                {{ useflow.usesize }} / {{ useflow.size }}
              </div>
              <div class="w-full">
                <el-progress
                  :percentage="useflow.percentagesize"
                  :color="
                    useflow.percentagesize > 80
                      ? '#ef4444'
                      : useflow.percentagesize > 60
                      ? '#f59e0b'
                      : '#3b82f6'
                  "
                  :stroke-width="6"
                  class="!mb-0"
                />
              </div>
            </div>
            <div class="bg-gray-50 dark:bg-dark-secondary rounded-lg p-4">
              <div
                class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"
              >
                月流量
              </div>
              <div
                class="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-2"
              >
                {{ useflow.useflow }} / {{ useflow.flow }}
              </div>
              <div class="w-full">
                <el-progress
                  :percentage="useflow.percentageflow"
                  :color="
                    useflow.percentageflow > 80
                      ? '#ef4444'
                      : useflow.percentageflow > 60
                      ? '#f59e0b'
                      : '#3b82f6'
                  "
                  :stroke-width="6"
                  class="!mb-0"
                />
              </div>
            </div>
          </div>
          <div class="flex justify-center pt-2" v-if="isAdmin">
            <el-upload
              class="w-full"
              :disabled="!!percentage"
              action="https://jsonplaceholder.typicode.com/posts/"
              :auto-upload="true"
              :http-request="request"
              :show-file-list="false"
            >
              <el-button
                :disabled="!!percentage"
                ref="buttonRef"
                size="default"
                type="primary"
                class="!w-full !py-3"
              >
                <el-icon :size="16">
                  <Upload />
                </el-icon>
                <span class="ml-2">
                  {{ percentage ? "上传中..." + percentage + "%" : "上传文件" }}
                </span>
              </el-button>
            </el-upload>
          </div>
        </div>
      </div>
    </div>
    <!-- 文件列表区域 -->
    <div
      class="bg-white dark:bg-dark-primary rounded-lg shadow-soft overflow-hidden"
      v-if="count"
      v-loading="loading"
    >
      <!-- 移动端卡片视图 -->
      <div class="p-4 space-y-4">
        <div
          class="bg-gray-50 dark:bg-dark-secondary rounded-lg border border-gray-200 dark:border-dark-border hover:shadow-lg transition-all duration-300 overflow-hidden file-card-hover animate-slide-up"
          v-for="(v, key) in tableDate"
          :key="key"
          :style="{ animationDelay: `${key * 50}ms` }"
        >
          <div class="p-4">
            <div class="flex justify-between items-start mb-3">
              <div class="flex-1 min-w-0">
                <div
                  class="text-base font-medium text-gray-900 dark:text-gray-100 truncate"
                  :title="v.name"
                >
                  {{ v.name }}
                </div>
                <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  {{ v.type || "无类型" }}
                </div>
              </div>
            </div>
            <div class="space-y-2">
              <div class="flex items-center justify-between text-sm">
                <span class="text-gray-600 dark:text-gray-300">上传时间:</span>
                <span class="text-gray-900 dark:text-gray-100 font-medium">{{
                  TimeYH2(v.createdAt)
                }}</span>
              </div>
              <div class="flex items-center justify-between text-sm">
                <span class="text-gray-600 dark:text-gray-300">文件大小:</span>
                <span class="text-gray-900 dark:text-gray-100 font-medium">{{
                  renderSize(Number(v.size))
                }}</span>
              </div>
            </div>
            <div
              class="flex justify-end space-x-2 mt-4 pt-4 border-t border-gray-200 dark:border-dark-border"
            >
              <el-tooltip
                effect="dark"
                content="下载链接有效期：5分钟"
                placement="top"
              >
                <el-button
                  :icon="Download"
                  size="small"
                  @click="download(v)"
                  class="!text-sm"
                >
                  下载
                </el-button>
              </el-tooltip>
              <el-button
                size="small"
                v-show="isAdmin"
                @click="del(v)"
                type="danger"
                class="!text-sm"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 分页器 -->
    <div class="flex justify-center mt-6" v-if="count">
      <el-pagination
        :page-size="limit"
        :total="count"
        @current-change="change"
        :layout="paginationLayout"
        :current-page="Math.floor(offset / limit) + 1"
        class="!bg-transparent"
      ></el-pagination>
    </div>

    <!-- 空状态 -->
    <div
      v-if="!count"
      class="bg-white dark:bg-dark-primary rounded-lg shadow-soft p-12 text-center"
    >
      <el-empty
        image="https://cdn.hterobot.com/JOY/oj_1_1/Not%20Found%20illustration.png"
        description="暂无文件"
        class="!my-0"
      >
        <template #description>
          <p class="text-gray-500 dark:text-gray-400 text-base">
            还没有上传任何文件，点击上方按钮开始上传吧！
          </p>
        </template>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Download, Upload } from "@element-plus/icons-vue";
import OSS from "ali-oss";
import {
  ElButton,
  ElMessage,
  ElMessageBox,
  ElNotification,
  ElUpload,
  UploadRequestOptions,
} from "element-plus";
import { debounce } from "underscore";
import { v4 } from "uuid";
import { computed, h, onMounted, ref, watch } from "vue";
import {
  asynccreateteamfile,
  asyncdelectteamfile,
  asyncgetteamfile,
  asyncgetteamflow,
  asyncupdateteamflow,
  asyncuploadAccess,
  ossupload,
} from "../../../api";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TimeYH2 } from "../../../util/time";
import { updateoss2 } from "../../../util/updateoss";
import { useStore } from "vuex";
import { Storekey } from "../../../interface";
const store = useStore(Storekey);

const flow = ref<Studycodemodel.Iteamflow>();
async function setflow() {
  try {
    flow.value = await asyncgetteamflow({ teamid: teamid?.value });
  } catch (e) {
    flow.value = undefined;
    console.log(e);
  }
}
const user = computed(() => {
  return store.state.user;
});
const teamid = computed(() => {
  return user.value?.teamid;
});

const isAdmin = computed(() => {
  return user.value?.type === "admin" || user.value?.type === "manage";
});

const tableDate = ref<Studycodemodel.Iteamfile[]>([]);
const percentage = ref(0);

// 响应式分页布局
const paginationLayout = computed(() => {
  // 检测屏幕宽度，在小屏幕上使用简化布局
  if (typeof window !== "undefined" && window.innerWidth < 768) {
    return "prev, pager, next";
  }
  return "total, prev, pager, next, jumper";
});

// 监听窗口大小变化
const { width } = window.screen || { width: 1024 };

async function del(V: Studycodemodel.Iteamfile) {
  if (!isAdmin.value) {
    ElMessage.error("没有权限");
  }
  ElMessageBox.confirm("确定要删除?", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "",
    type: "warning",
  })
    .then(async () => {
      try {
        await asyncdelectteamfile(V);
        if (V.url) {
          await o.value?.delete(V.url);
        }
        start();
      } catch (e) {
        ElMessage({
          message: String(e),
          type: "error",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}

const useflow = computed(() => {
  const {
    usesize = 0,
    size = 1021 * 1024 * 1024 * 5,
    useflow = 0,
  } = flow.value || {};
  const _flow = flow.value?.flow || 1021 * 1024 * 1024 * 10;
  return {
    size: renderSize(size),
    usesize: renderSize(usesize),
    flow: renderSize(_flow),
    useflow: renderSize(useflow),
    percentageflow: Math.floor((useflow / _flow) * 100),
    percentagesize: Math.floor((usesize / size) * 100),
    _usesize: usesize,
    _size: size,
    _flow: _flow,
    _useflow: useflow,
  };
});

async function download(name: Studycodemodel.Iteamfile) {
  if (useflow.value._useflow > useflow.value._flow) {
    ElMessage.error("本月团队资料流量已用完，如需帮助请联系助教老师或管理员");
    return;
  }
  const data = o.value?.signatureUrl(String(name.url), {
    expires: 300,
  });
  await asyncupdateteamflow({
    ID: flow.value?.ID,
    useflow: flow.value?.useflow,
    size: name.size,
    teamid: teamid.value,
    name: name.name,
    teamfileid: name.ID,
  });
  window.open(data, "_blank");
  setflow();
}

const upload = ref<typeof ElUpload>();
async function request(option: UploadRequestOptions) {
  if (upload.value) upload.value.clearFiles();
  if (option.file.size > 1024 * 1024 * 1024) {
    ElMessage.warning(
      "提示：文件资料大小为1G以内，如需上传更大文件请联系助教老师"
    );
    return;
  }

  if (useflow.value._usesize > useflow.value._size) {
    ElMessage.error("团队存储空间已满，如需帮助请联系助教老师或管理员");
    return;
  }
  if (option.file.name.length > 128) {
    ElMessage.error("文件名称最大长度128");
    return;
  }
  try {
    const res = await asyncuploadAccess({ teamid: teamid.value });
    const v = v4();
    const d = await updateoss2(
      [option.file],
      {
        bucket: "ojteam",
        url: `${teamid.value}/${v}/${option.file.name}`,
        res,
      },
      () => {},
      {
        progress,
      }
    );
    percentage.value = 0;
    const sp = option.file.name.split(".");
    await asynccreateteamfile({
      name: option.file.name,
      url: d.name,
      size: option.file.size,
      type: sp.length === 1 ? "" : sp.pop(),
      teamid: teamid.value,
    });
    start();
    setflow();
  } catch (e: any) {
    console.log(e);
    ElMessage.error(e);
  }
}

function progress(per: number) {
  percentage.value = Math.floor(per * 100);
}

function renderSize(value: number) {
  if (!value) {
    return "0 Bytes";
  }
  var unitArr = new Array(
    "Bytes",
    "KB",
    "MB",
    "GB",
    "TB",
    "PB",
    "EB",
    "ZB",
    "YB"
  );
  var index = 0;
  var srcsize = parseFloat(String(value));
  index = Math.floor(Math.log(srcsize) / Math.log(1024));
  var size = srcsize / Math.pow(1024, index);
  return size.toFixed(2) + unitArr[index];
}

const count = ref(0);
const offset = ref(0);
const limit = ref(10);
const loading = ref(false);
const name = ref("");
function debounce1() {
  return debounce(() => {
    let _like: [keyof Studycodemodel.Iteamfile, any] | undefined;
    if (name.value) {
      _like = ["name", name.value];
    }
    loading.value = true;
    asyncgetteamfile({
      _offset: offset.value,
      _limit: limit.value,
      _like,
      teamid: teamid.value,
    }).then((e) => {
      loading.value = false;
      tableDate.value = e.rows;
      count.value = e.count;
    });
    setflow();
  }, 300);
}
const start = debounce1();

watch([offset, limit, name], () => {
  start();
});

const o = ref<OSS>();

onMounted(async () => {
  const res = await ossupload();
  o.value = new OSS({
    region: "oss-cn-qingdao",
    accessKeyId: res.accessKeyId,
    accessKeySecret: res.accessKeySecret,
    stsToken: res.securityToken,
    bucket: "ojteam",
    refreshSTSToken: async () => {
      const info = await ossupload();
      return {
        accessKeyId: info.accessKeyId,
        accessKeySecret: info.accessKeySecret,
        stsToken: info.securityToken,
      };
    },
  });
  start();
});

function change(r: number) {
  offset.value = (r - 1) * 10;
}
</script>

<style scoped>
/* 确保Element Plus组件与Tailwind的兼容性 */
:deep(.el-progress-bar__outer) {
  @apply bg-gray-200 dark:bg-gray-600 rounded-full;
}

:deep(.el-progress-bar__inner) {
  @apply bg-gradient-to-r from-primary-500 to-primary-600 rounded-full;
}

:deep(.el-button--primary) {
  @apply !bg-gradient-to-r !from-primary-500 !to-primary-600 !border-primary-500 hover:!from-primary-600 hover:!to-primary-700 hover:!border-primary-600 !shadow-lg hover:!shadow-xl transition-all duration-300;
}

:deep(.el-button--danger) {
  @apply !bg-gradient-to-r !from-red-500 !to-red-600 !border-red-500 hover:!from-red-600 hover:!to-red-700 hover:!border-red-600 !shadow-lg hover:!shadow-xl transition-all duration-300;
}

:deep(.el-pagination) {
  @apply !text-gray-700 dark:!text-gray-300;
}

:deep(.el-pagination .btn-next),
:deep(.el-pagination .btn-prev) {
  @apply !bg-white dark:!bg-dark-secondary !text-gray-700 dark:!text-gray-300 !border-gray-300 dark:!border-dark-border hover:!bg-gray-50 dark:hover:!bg-gray-600 transition-all duration-200;
}

:deep(.el-pagination .el-pager li) {
  @apply !bg-white dark:!bg-dark-secondary !text-gray-700 dark:!text-gray-300 !border-gray-300 dark:!border-dark-border hover:!bg-gray-50 dark:hover:!bg-gray-600 transition-all duration-200;
}

:deep(.el-pagination .el-pager li.is-active) {
  @apply !bg-gradient-to-r !from-primary-500 !to-primary-600 !text-white !border-primary-500 !shadow-md;
}

:deep(.el-empty) {
  @apply !text-gray-500 dark:!text-gray-400;
}

:deep(.el-loading-mask) {
  @apply !bg-white !bg-opacity-90 dark:!bg-dark-primary dark:!bg-opacity-90 backdrop-blur-sm;
}

:deep(.el-upload) {
  @apply !block !w-full;
}

/* 确保svg图标能正确显示 */
svg {
  @apply fill-current transition-colors duration-200;
}

/* 文件卡片悬停效果 */
.file-card-hover {
  @apply transform hover:scale-105 hover:-translate-y-1;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  @apply w-2;
}

::-webkit-scrollbar-track {
  @apply bg-gray-100 dark:bg-gray-700 rounded-full;
}

::-webkit-scrollbar-thumb {
  @apply bg-gray-300 dark:bg-gray-500 rounded-full hover:bg-gray-400 dark:hover:bg-gray-400;
}

/* 加载动画优化 */
:deep(.el-loading-spinner) {
  @apply !text-primary-500;
}

/* 响应式字体大小 */
@media (max-width: 640px) {
  .responsive-text-lg {
    @apply text-base;
  }

  .responsive-text-base {
    @apply text-sm;
  }

  .responsive-text-sm {
    @apply text-xs;
  }
}

/* 暗色模式过渡动画 */
* {
  @apply transition-colors duration-300;
}

/* 渐变背景动画 */
@keyframes gradient-shift {
  0%,
  100% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
}

.gradient-bg {
  background: linear-gradient(-45deg, #667eea, #764ba2, #f093fb, #f5576c);
  background-size: 400% 400%;
  animation: gradient-shift 15s ease infinite;
}
</style>
